const { api } = require('../../utils/api.js');

Page({
  data: {
    userInfo: null,
    phoneNumber: '',
    qrCodeData: '',
    qrCodeUrl: '',
    isLogin: false,
    hasPhoneNumber: false,
    isLoading: true
  },
  
  onLoad: function() {
    this.checkUserStatus();
  },
  
  onShow: function() {
    this.checkUserStatus();
  },
  
  checkUserStatus: function() {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    
    if (!token) {
      this.setData({
        isLogin: false,
        isLoading: false
      });
      return;
    }
    
    this.setData({ isLogin: true });
    
    // 获取用户资料
    api.getUserProfile().then(res => {
      if (res.status === 'success' && res.user) {
        const hasPhoneNumber = !!(res.user.car_owner && res.user.car_owner.phone_number);
        
        this.setData({
          userInfo: res.user,
          phoneNumber: hasPhoneNumber ? res.user.car_owner.phone_number : '',
          hasPhoneNumber: hasPhoneNumber
        });
        
        if (hasPhoneNumber) {
          // 获取二维码
          this.fetchQRCode();
        } else {
          this.setData({ isLoading: false });
        }
      }
    }).catch(err => {
      console.error('获取用户资料失败', err);
      this.setData({ isLoading: false });
      
      if (err.statusCode === 401) {
        // 身份验证失败，清除登录信息
        wx.removeStorageSync('token');
        this.setData({ isLogin: false });
      }
    });
  },
  
  fetchQRCode: function() {
    this.setData({ isLoading: true });
    
    api.getQrCode().then(res => {
      if (res.status === 'success' && res.qr_code_url) {
        this.setData({
          qrCodeUrl: res.qr_code_url,
          phoneNumber: res.phone_number
        });
      }
    }).catch(err => {
      console.error('获取二维码失败', err);
      wx.showToast({
        title: '获取二维码失败',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ isLoading: false });
    });
  },
  
  goToLogin: function() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },
  
  goToCreateQR: function() {
    wx.navigateTo({
      url: '/pages/createQR/createQR'
    });
  },
  
  saveQRCode: function() {
    if (!this.data.qrCodeUrl) {
      wx.showToast({
        title: '二维码未加载完成',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    
    // 下载二维码图片
    wx.downloadFile({
      url: this.data.qrCodeUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存到相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              });
            },
            fail: (err) => {
              console.error('保存到相册失败', err);
              wx.showToast({
                title: '保存失败，请确认授权',
                icon: 'none'
              });
            }
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '下载二维码失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  
  shareQRCode: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  
  // 分享给朋友
  onShareAppMessage: function() {
    return {
      title: '我的挪车码 - 挪车小助手',
      path: '/pages/myQR/myQR',
      imageUrl: '/images/my_qr.png',
      desc: '查看和管理我的专属挪车码'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: '我的挪车码 - 挪车小助手',
      imageUrl: '/images/my_qr.png',
      query: ''
    };
  }
}); 